﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Rung.Soft.Jx3Tookit
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //添加找不到程序集的处理函数
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        //手动指定程序集的位置
        static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
        {
            string addonFolder = null;

            #region 查找插件文件夹
            addonFolder = Rung.Soft.Jx3Tookit.Business.ConstValue.AddonFolder;
            string assemblyFile = System.IO.Path.Combine(addonFolder, e.Name.Split(',')[0].Trim() + ".dll");
            if (System.IO.File.Exists(assemblyFile))
            {
                return System.Reflection.Assembly.LoadFrom(assemblyFile);
            } 
            #endregion

            #region 查找 .Net Framework 文件夹
            //// C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\zh-Hans\mscorlib.resources.dll
            string frameworkPath = null;
            string versionPath = null;
            string cunsionPath = null;

            //// frameworkPath
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey software = rk.OpenSubKey("SOFTWARE", false);//对应HKEY_LOCAL_MACHINE基项分支
            RegistryKey product = software.OpenSubKey(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework", false);//打开Software项
            frameworkPath = product.GetValue("InstallRoot").ToString();
            //rk.Close();

            //// versionPath
            //versionPath = Environment.Version.ToString();

            //// cunsionPath

            //assemblyFile = System.IO.Path.Combine(frameworkPath, versionPath, cunsionPath, e.Name.Split(',')[0].Trim() + ".dll");
            //if (System.IO.File.Exists(assemblyFile))
            //{
            //    return System.Reflection.Assembly.LoadFrom(assemblyFile);
            //} 
            #endregion

            assemblyFile = e.Name.Split(',')[0].Trim() + ".dll";
            return System.Reflection.Assembly.LoadFrom(assemblyFile);
        }
    }
}
